#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import os.path
import re
import tornado.auth
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import unicodedata
import datetime
import pymongo

class BaseHandler(tornado.web.RequestHandler):
	@property
	def db(self):
		return pymongo.Connection('localhost').domaindb


class UserHandler(BaseHandler):
	def get(self):
		users = self.getAllUsers()
		self.render('user.html',entries=users)

	def post(self):
		#self.write('add user')
		self.addUser()

	def addUser(self):
		username = self.get_argument('username')
		userpass = self.get_argument('userpass')
		createtime = datetime.datetime.now().isoformat()
		lasttime = None
		self.db.users.save({'username':username,'userpass':userpass,'createtime':createtime,'lasttime':lasttime})
		#self.render('user.html',entries=self.getAllUsers())
		self.write('saved')

	def getAllUsers(self):
		return self.db.users.find()
		#users = [{username:'tedi3231',userpass:'loveyuanyuan',createtime:'2011-04-04'}]
		#return users

class LoginHandler( tornado.web.RequestHandler):
	def get(self):
		self.write('helow,login')

	def post(self):
		self.write('helow post')

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

class ProductHandler(tornado.web.RequestHandler):
	def get(self):
		self.write('product list parms\n')
		parms = self.get_arguments('parm1')

		if parms:
			self.write('parm1.count %s ' % len(parms))
		
		for a in parms:
			self.write('p=' + a + '<br/>')

class Application(tornado.web.Application):
	def __init__(self):
		handlers = [
		    (r"/", MainHandler),
		    (r'/product', ProductHandler),
			(r'/login',LoginHandler),
			(r'/user',UserHandler),
		]
		
		settings = dict(
		    blog_title=u"Tornado Blog",
		    template_path=os.path.join(os.path.dirname(__file__), "templates"),
		    static_path=os.path.join(os.path.dirname(__file__), "static"),
		    #ui_modules={"Entry": EntryModule},
		    xsrf_cookies=True,
		    cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
		    login_url="/login",
		)
		
		tornado.web.Application.__init__(self, handlers, **settings)    
    
    
def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()
